/**
 * this files imports or updates exisiting entries with pubchem compound properties
 */

import edu.ucdavis.genomics.metabolomics.binbase.connector.references.pubchem.PubchemSubstanceSDFResolver
import org.apache.log4j.Logger
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.*

//configuration file
def config = new ConfigSlurper().parse(new File('grails-app/conf/PathConfiguration.groovy').toURL())

Logger logger = Logger.getLogger("ImportPubchem")

String tempDir = config.files.pubchem.substance

FileHelper.workOnDir(tempDir, {File file ->
  PubchemInchiSubstance sub = new PubchemInchiSubstance()
  SdfToInchi.sdfToInchi(new FileInputStream(file), sub)

}, logger, ".sdf")

/**
 * imports a pubchem compound for each found inchi
 */
class PubchemInchiSubstance implements InchFinder {


  public void foundInchi(String myInchi, Map<java.lang.Object, java.lang.Object> objectObjectMap) throws Exception {

    Logger logger = Logger.getLogger("ImportPubchem")
    logger.debug "checking if inchi is acceptable"
    if (myInchi != null && myInchi.size() > 0) {

      PubchemSubstanceSDFResolver resolver = new PubchemSubstanceSDFResolver()
      resolver.prepare(objectObjectMap)

      Compound compound = CompoundHelper.getCompound(resolver.getInchi(), resolver.getInchiKey(), logger)

      //save the cas number, if it's available
      CompoundHelper.storeCas(resolver.getCas(), compound, logger)

      //sets the sid for this compound
      CompoundHelper.updateSID(logger, compound, Integer.parseInt(resolver.getSid()))

      List<String> syn = resolver.getSynonyms()

      for (Synonym s: compound.synonyms) {
        for (int i = 0; i < syn.size(); i++) {
          if (s.name.equals(syn.get(i))) {
            logger.debug "already contains synonym '${syn.get(i)}' so skip it"
            syn.remove(i)
            i--
          }
        }
      }

      CompoundHelper.updatesTheCasNumber(resolver.getCas(), compound, logger)

      //save the compound to the database
      CompoundHelper.saveCompound(compound, logger)

    }
  }

}